import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, message, Steps, theme, Input, Form, Select, Space } from 'antd'
import CommonEditor from '../../components/CommonEditor/index'
import CommonUpload from '../../components/CommonUpload/index'
import { useApi } from '../../api/index'
import { useThrottle } from '../../utils'
//
const MyEditor = React.memo(CommonEditor)
const MyUpload = React.memo(CommonUpload)

// 表单格式
const steps = [
  {
    title: '基本信息',
    description: '新闻标题,新闻分类'
  },
  {
    title: '新闻内容',
    description: '新闻主体内容'
  },
  {
    title: '图片',
    description: '新闻背景图片'
  },
  {
    title: '提交',
    description: '提交审核'
  }
]

//下拉框
const { Option } = Select

// 输入框和babel标签的样式
const layout = {
  labelCol: {
    span: 1.8
  },
  wrapperCol: {
    span: 22.2
  }
}

function ArticlePublish() {
  const navigate = useNavigate()
  // 当前步骤
  const [current, setCurrent] = useState(0)
  //新闻分类下拉框选项
  const [type, setType] = useState([])
  //触发富文本编辑器提交
  const [editorSubmit, setEditorSubmit] = useState(0)

  // 新闻提交数据
  const data = useRef({
    title: '',
    type: '',
    content: '',
    articleImg: ''
  })

  //请求接口
  const { getArticleType, publishArticle } = useApi()

  //步骤一的表单对象
  const [form] = Form.useForm()

  //节流+提交,发布文章
  const handlerPublish = useThrottle(
    async () => {
      try {
        await publishArticle(data.current)
        message.success({
          content: '发布成功',
          duration: 2
        })
        navigate('/article')
      } catch (error) {
        message.error('异常')
        console.log('err', error)
      }
    },
    1000,
    true
  )

  //请求新闻分类数据
  useEffect(() => {
    ; (async () => {
      try {
        let res = await getArticleType()
        setType(res)
      } catch (error) {
        message.error('异常')
        console.log('err', error)
      }
    })()
  }, [])

  //下一步
  const next = () => {
    // 表单校验
    if (current == 0) {
      form.validateFields().then(
        res => {
          //表单提交
          form.submit()
          setCurrent(current + 1)
        },
        err => {
          message.error('选项不能为空')
        }
      )
    } else if (current == 1) {
      //通过修改editorSubmit，触发子组件提交数据，并跳转页面
      setEditorSubmit(editorSubmit + 1)
    } else if (current == 2) {
      if (data.current.articleImg == '') {
        message.error('背景图片不能为空')
      } else {
        setCurrent(current + 1)
      }
    }
  }
  // 上一步
  const prev = () => {
    setCurrent(current - 1)
  }

  //保存富文本编辑器内容
  const storeEditor = useCallback(res => {
    // console.log('xx', res)

    if (res.content == '' || res.content === '<p><br></p>') {
      message.error('内容不能为空')
      return
    }

    data.current = {
      ...data.current,
      ...res
    }
    //跳转页面
    setCurrent(current => current + 1)
  }, [])

  //文件上传
  const uploaded = useCallback(articleImg => {
    data.current = {
      ...data.current,
      articleImg
    }
  }, [])

  //form表单，分类，标题保存
  const onFinish = values => {
    data.current = {
      ...data.current,
      ...values
    }
  }

  return (
    <>
      {/* 盒子 */}
      <div className="p-[.5rem]">
        {/* 表头 */}
        <div className="h-[.5rem] text-[.3rem] font-bold text-left ml-[.075rem] mb-[.2rem]">
          撰写新闻
        </div>
        {/* 步骤条 */}
        <Steps current={current} className="" items={steps} />
        {/* 内容区 */}
        <div className="h-[7rem] flex flex-col items-center ">
          {/* 表单内容 */}
          <div className="w-[19.5rem] mt-[1rem]">
            {/* 步骤一的表单 */}
            <div className={current == 0 ? '' : 'hidden'}>
              <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
                <Form.Item
                  name="title"
                  label="新闻标题"
                  rules={[
                    {
                      required: true,
                      message: '请填写标题'
                    }
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="type"
                  label="新闻分类"
                  rules={[
                    {
                      required: true,
                      message: '请选择分类'
                    }
                  ]}
                >
                  <Select allowClear className="text-start">
                    {type?.map(item => {
                      return (
                        item.status == '0' && (
                          <Option value={item.typeName} key={item.id}>
                            {item.typeName}
                          </Option>
                        )
                      )
                    })}
                  </Select>
                </Form.Item>
              </Form>
            </div>

            {/* 步骤二的富文本编辑器 */}
            <div className={`h-[4.375rem] ${current == 1 ? '' : 'hidden'}`}>
              <MyEditor editorSubmit={editorSubmit} storeEditor={storeEditor}></MyEditor>
            </div>

            {/* 步骤三的文件上传 */}
            <div className={`h-[4.375rem] ${current == 2 ? '' : 'hidden'}`}>
              <MyUpload uploaded={uploaded}></MyUpload>
            </div>
          </div>

          {/* 步骤按钮 */}
          <div className="w-[100%] flex justify-start mt-[.8rem]">
            {current < steps.length - 1 && (
              <Button type="primary" onClick={next}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" onClick={handlerPublish}>
                提交
              </Button>
            )}
            {current > 0 && (
              <Button
                style={{
                  margin: '0 8px'
                }}
                onClick={prev}
              >
                上一步
              </Button>
            )}
          </div>
        </div>
      </div>
    </>
  )
}

export default ArticlePublish
